﻿using System;
using System.IO;
using System.Linq;
using Autofac;
using Autofac.Extras.DynamicProxy;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace Bean.Infrastructure.Autofac
{
    /// <summary>
    /// 自动化注入
    /// </summary>
    public static class AutofacExtensions
    {

        /// <summary>
        /// 注入服务
        /// </summary>
        public static void RegisterAppService(this ContainerBuilder builder, string projectName)
        {
            var dlls = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory), projectName);

            foreach (var dll in dlls)
            {
                var assembly = Assembly.LoadFrom(dll);

                //注入控制器
                builder.RegisterAssemblyTypes(assembly).Where(t => typeof(ControllerBase).IsAssignableFrom(t))
                    .PropertiesAutowired(new AutowiredPropertySelector());

                //瞬时注入
                builder.RegisterAssemblyTypes(assembly)
                    .Where(t => t.IsClass && t.GetInterfaces().Contains(typeof(ITransientService)))
                    .InstancePerDependency()
                    .AsImplementedInterfaces()
                    .EnableInterfaceInterceptors()
                    .PropertiesAutowired(new AutowiredPropertySelector());

                //单例注入
                builder.RegisterAssemblyTypes(assembly)
                    .Where(t => t.IsClass && t.GetInterfaces().Contains(typeof(ISingletonService)))
                    .SingleInstance()
                    .AsImplementedInterfaces()
                    .EnableInterfaceInterceptors()
                    .PropertiesAutowired(new AutowiredPropertySelector());

                //作用域
                builder.RegisterAssemblyTypes(assembly)
                  .Where(t => t.IsClass && t.GetInterfaces().Contains(typeof(IScopedService)))
                  .InstancePerLifetimeScope()
                  .AsImplementedInterfaces()
                  .EnableInterfaceInterceptors()
                  .PropertiesAutowired(new AutowiredPropertySelector());
            }
        }
    }
}
